package com.yunshang.shoppingmall.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunshang.shoppingmall.common.MessageConstants;
import com.yunshang.shoppingmall.common.Response;
import com.yunshang.shoppingmall.common.layuiJson;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Controller
public class OrderController {

    @Autowired
    OrderService orderService;
    @Autowired
    CartService cartService;
    @Autowired
    OrderDetailsService orderDetailsService;
    @Autowired
    AddressService addressService;
    @Autowired
    FreightService freightService;
    @Autowired
    AreaService areaService;

    @Autowired
    ChangeProductService changeProductService;
    @Autowired
    OrderAddressService orderAddressService;
    @RequestMapping("/getOrderList")
    @ResponseBody
    //订单列表 首次打开查询
    public String getOrderList(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit)
    {
        PageHelper.startPage(page,limit);
        List<Order> orderList=orderService.selectAll();
        PageInfo page1 = new PageInfo(orderList);
        return layuiJson.layuiJsonList(orderList,(int)page1.getTotal());
    }

    //全部订单页面 条件查询
    @RequestMapping("/selectOrderList")
    @ResponseBody
    public String selectOrderList(@RequestParam("page") Integer page,
                                  @RequestParam("limit") Integer limit,
                               @RequestParam("orderStatus") String orderStatus,
                               @RequestParam("payStatus") String payStatus,
                               @RequestParam("deliveStatus") String deliveStatus,
                                  @RequestParam("keywords") String keywords,
                                  @RequestParam("userNo") String userNo) {
        //System.out.println(orderStatus + "--" + payStatus + "--" + deliveStatus+ "--" + page+ "--" + keywords+ "--" + limit);
        PageHelper.startPage(page, limit);
        List<Order> orderList = orderService.selectQuery(orderStatus,payStatus,deliveStatus,keywords,userNo);
        //System.out.println(orderList.size());
        PageInfo page1 = new PageInfo(orderList);
        return layuiJson.layuiJsonList(orderList, (int) page1.getTotal());
    }

    @RequestMapping("/orderList")
    public String orderList()
    {
        return "order/orderList";
    }


    //订单详情
    @RequestMapping("/getOrderDetails")
    public ModelAndView getOrderDetails(HttpServletRequest request,String No,String userId){
        ModelAndView modelAndView=new ModelAndView("order/orderDetails");
        OrderDetails orderDetails=orderDetailsService.selectOrderDetailsByOrderNo(No,userId+"");
        List<OrderDetailsProduct> orderDetailsProductList=orderDetailsService.selectOrderDetailsProductByOrderNo(No);//通过订单号查询
        for (OrderDetailsProduct orderDetailsProduct:orderDetailsProductList ) {
            String logStrs=orderDetailsProduct.getLogisticsNo()==null?"":orderDetailsProduct.getLogisticsNo();
            List<String> list=new ArrayList<>();
            for (String str: logStrs.split(",")) {
                if(str!=null&&!str.equals("")){
                    list.add(str);
                }
            }
            orderDetailsProduct.setLogList(list);
        }
        List<ChangeProduct> changeProductList=changeProductService.selectList(No);
        List<Cart> cartList=cartService.selectList(No);
        modelAndView.addObject("orderDetails",orderDetails);
        modelAndView.addObject("orderDetailsProductList",orderDetailsProductList);
        modelAndView.addObject("changeProductList",changeProductList);
        modelAndView.addObject("cartList",cartList);
        return modelAndView;
    }

    //改单修改收货地址
    @RequestMapping("/editLogAddress")
    @ResponseBody
    public ModelAndView editLogAddress(String id){
        Integer idInt=Integer.parseInt(id);
        ModelAndView modelAndView=new ModelAndView("order/editLogAddress");
        Address address=addressService.selectById(idInt);
        Address address1=addressService.selectLogType(idInt);
        address.setLogisticsType(address1.getLogisticsType());
        modelAndView.addObject("address",address);
        return modelAndView;
    }

    //带出地址信息
    @ResponseBody
    @RequestMapping("/selectAreaList")
    public List<Area> selectAreaList(String parentId,String level){
        List<Area> areaList=areaService.selectAreaList(Integer.parseInt(parentId),Integer.parseInt(level));
        return areaList;
    }

    //修改收货地址
//    @ResponseBody
//    @RequestMapping("/editLogAddressData")
//    public Response editLogAddressData(HttpServletRequest request,
//                                   @RequestParam("id") String id,
//                                   @RequestParam("name") String name,
//                                   @RequestParam("phone") String phone,
//                                   @RequestParam("address") String address,
//                                   @RequestParam("detailAddress") String detailAddress,
//                                       @RequestParam("logtype") String logtype,
//                                       @RequestParam("orderNo") String orderNo,
//                                       @RequestParam("userId") String userId)throws Exception{
//        //System.out.println(id+"--"+name+"--"+phone+"--"+address+"--"+detailAddress);
//        Address address1=new Address();
//        if(!address.equals("0")) {
//            String[] names = address.split(",");
//            address1.setCityId(Integer.parseInt(names[1]));
//            address1.setProvinceId(Integer.parseInt(names[0]));
//            address1.setAreaId(Integer.parseInt(names[2]));
//        }
//        address1.setName(name);
//        address1.setPhone(phone);
//        address1.setDetailAddr(detailAddress);
//        address1.setIsdefault(0);//1 默认地址 0普通地址
//        Integer res=addressService.insertSelective(address1);
//        Integer res1=cartService.updateLogType(Integer.parseInt(logtype),orderNo,address1.getId());
//        if(res>=0&&res1>=0){
//            return new Response(MessageConstants.MSG_SYS_ERROR, 1, "成功!");
//        }
//        return new Response(MessageConstants.MSG_SYS_ERROR, 0, "失败!");
//    }

    //改单添加产品到购物车

    /**
     *
     * @param request
     * @param -tabInfo 改单产品信息
     * @param -orderNo 订单号
     * @param -id 地址id
     * @param -name 收货人姓名
     * @param -phone 电话
     * @param -address 地址
     * @param -detailAddress 详细地址
     * @param -logtype 物流类型
     * @param -userId 用户id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/changeProductCart",method = RequestMethod.POST)
    public Response changeProductCart(HttpServletRequest request)throws Exception{
        String tabInfo=request.getParameter("tabInfo");
        String orderNo=request.getParameter("orderNo");
        String id=request.getParameter("id");
        String name=request.getParameter("name");
        String phone=request.getParameter("phone");
        String address=request.getParameter("address");
        String detailAddress=request.getParameter("detailAddress");
        String logtype=request.getParameter("logtype");
        String userId=request.getParameter("userId");
        String remark=request.getParameter("remark");
        Order order=orderService.selectByNo(orderNo);
        if(order!=null){
            int isOrderForm=order.getIsOrderFrom()==null?0:order.getIsOrderFrom();
            if(isOrderForm!=0){
                return new Response(MessageConstants.MSG_SUCCESS,-2,"已导单不允许修改");
            }
        }

        System.out.println("userid:"+userId);
        HttpSession session = request.getSession();
        int adminUserId=0;
        int idint=0,logtypeint=0;
        try {
            idint=Integer.parseInt(id);
            adminUserId = Integer.parseInt(session.getAttribute("adminId").toString());
            logtypeint=Integer.parseInt(logtype);
        }catch (Exception e){
        }
        if(logtypeint==1){//自提
            if(order!=null){
                order.setLogisticalType(1);
                order.setOrderStatus("704");
                int res=orderService.updateByPrimaryKeySelective(order);
            }
        }
        //System.out.println("logtypeint:"+logtypeint);
        Integer res2=0;
        OrderAddress orderAddress=new OrderAddress();
        String []strings=tabInfo.split("-");//分解改单产品信息
        for (String item:strings) {
            if("".equals(item)){
                orderAddress=orderAddressService.selectByPrimaryKey(idint);
                //修改地址信息
                if(!address.equals("0")) {
                    String[] names = address.split(",");
                    if(names.length==3){
                        orderAddress.setCityId(Integer.parseInt(names[1]));
                        orderAddress.setProvinceId(Integer.parseInt(names[0]));
                        orderAddress.setAreaId(Integer.parseInt(names[2]));
                    }
                }
                orderAddress.setName(name);
                orderAddress.setPhone(phone);
                orderAddress.setDetailAddr(detailAddress);
                orderAddress.setLogType(logtypeint);
                 orderAddress.setRemark(remark);
                Integer res=orderAddressService.updateByPrimaryKeySelective(orderAddress);
                res2=res;
            }else {
                System.out.println("tabInfo"+tabInfo);
                String idA="0",nameA="",number="0",price="0";
                try {
                    idA=item.split(",")[0];
                    nameA=item.split(",")[1];
                    number=item.split(",")[2];
                    price=item.split(",")[3];
                }catch (Exception e){}
                if(!"0".equals(number)){
//           Cart cart1=cartService.selectByOrderNo(orderNo);
//            cart1.setType(3);
//            cartService.updateByPrimaryKeySelective(cart1);
                    Cart cart = new Cart();
                    cart.setpCount(Integer.parseInt(number));
                    cart.setProductName(nameA);
                    cart.setProductPrice(BigDecimal.valueOf(Double.valueOf(price)));
                    cart.setUserId(Integer.parseInt(userId));
                    cart.setCartStatus("501");
                    cart.setOrderNo(orderNo);
                    cart.setTime(new Date());
                    cart.setOperationId(adminUserId);
                    cart.setOperationTime(new Date());
                    cart.setRemark(remark);
                    cart.setLogisticsType(Integer.parseInt(logtype));
                    cart.setType(1);
                    cart.setAddressId(orderAddress.getId());
                    int res3=cartService.insertSelective(cart);
                    res2=res3;
                }
            }

        }
        System.out.println(res2+"--");
        return new Response(MessageConstants.MSG_SUCCESS,res2,"");
    }




}
